<template>
  <div class="mala-album" v-show="visiable">
    <div class="mala-album-top">
      <div class="mala-album-top-close" @click="closeClickHandle">
        <img src="./assets/close.png" alt="关闭图标">
      </div>
    </div>
    <div class="mala-album-slider">
      <div class="mala-album-slider-control">
        <div class="mala-album-slider-control-left" @click="() => controlClickHandle(false)">
          <img src="./assets/left.png" alt="左箭头图标">
        </div>
        <div class="mala-album-slider-control-right" @click="() => controlClickHandle(true)">
          <img src="./assets/right.png" alt="右箭头图标">
        </div>
      </div>
      <div class="mala-album-slider-image">
        <img ref="imgRef" :src="imgList[currentIndex]" alt="图片" />
      </div>
    </div>
    <div class="mala-album-preview">
      <Indicator :selectIndex="currentIndex">
        <div
          :class="['mala-album-preview-item', { active: currentIndex === index }]"
          v-for="(item, index) in imgList"
          :key="index"
          @click="() => itemClickHandle(index)">
          <img :src="item" alt="图片">
        </div>
      </Indicator>
    </div>
  </div>
</template>

<script>
export default {
  name: "mala-album"
}
</script>

<script setup>
import { ref, onMounted, watch } from "vue"
import Indicator from "../../indicator"
// 外部props
const props = defineProps({
  visiable: {
    type: Boolean,
    default: false
  },
  imgList: {
    type: Array,
    required: true
  }
})
const emits = defineEmits(["close"])
// 组件状态
const currentIndex = ref(0)
const imgRef = ref(null)
// 是否正在执行动画
let flag = false
// 事件处理
// 关闭事件
const closeClickHandle = () => {
  emits("close")
}
// 添加动画函数
const animationControl = (isNext = true) => {
  const className = "mala-album-slider-image-animation-" + (isNext ? "leave" : "enter")
  imgRef.value.className = className
  setTimeout(() => {
    imgRef.value.className = ""
    flag = false
  }, 300)
}
// 切换图片事件
const controlClickHandle = (isNext) => {
  if (flag) return
  flag = true
  let newIndex = isNext ? currentIndex.value + 1 : currentIndex.value - 1
  if (newIndex < 0) newIndex = props.imgList.length - 1
  if (newIndex > props.imgList.length - 1) newIndex = 0
  currentIndex.value = newIndex
  animationControl(isNext)
}
// 图片列表点击事件
const itemClickHandle = (index) => {
  const isNext = currentIndex.value < index
  currentIndex.value = index
  animationControl(isNext)
}
// 生命周期
onMounted(() => {
  // 监听显示与隐藏
  watch(() => props.visiable, (visiable) => {
    if (visiable) {
      document.body.style.overflow = "hidden"
    } else {
      document.body.style.overflow = "auto"
    }
  })
})
</script>
